<template>
  <div class="comment-list-container">
    <el-list :border="true" class="comment-list">
      <el-list-item v-for="comment in comments" :key="comment.id" class="comment-item">
        <template #default>
          <div class="comment-header">
            <el-avatar :size="40" :src="getAvatar(comment.author)" class="comment-avatar" />
            <div class="commenter-info">
              <h4 class="commenter-name">{{ comment.author }}</h4>
              <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
            </div>
          </div>
          
          <div class="comment-content">{{ comment.content }}</div>
          
          <div class="comment-actions">
            <el-button type="text" size="small" @click="replyComment(comment.id)">{{ '回复' }}</el-button>
            <el-button type="text" size="small" @click="likeComment(comment.id)">{{ '点赞' }}({{ comment.likes || 0 }})</el-button>
          </div>
          
          <el-input
            v-model="replyContent[comment.id]"
            type="textarea"
            :rows="2"
            placeholder="输入回复内容..."
            v-if="showReply[comment.id]"
            class="reply-input"
          />
          
          <el-button 
            v-if="showReply[comment.id]" 
            type="primary" 
            size="small" 
            @click="submitReply(comment.id)"
            class="reply-button"
          >
            发送
          </el-button>
          
          <el-list v-if="comment.replies && comment.replies.length > 0" class="reply-list">
            <el-list-item v-for="(reply, index) in comment.replies" :key="index" class="reply-item">
              <el-avatar :size="32" :src="getAvatar(reply.author)" class="reply-avatar" />
              <div class="reply-content">
                <span class="reply-author">{{ reply.author }}:</span>
                <span>{{ reply.content }}</span>
              </div>
            </el-list-item>
          </el-list>
        </template>
      </el-list-item>
    </el-list>
    
    <el-empty v-if="comments.length === 0" description="暂无评论"></el-empty>
  </div>
</template>

<script setup lang="ts">
// 生命周期钩子
onMounted(async () => {
  await fetchComments()
})

// 获取评论列表
const fetchComments = async () => {
  try {
    const data = await commentStore.fetchArticleComments(props.articleId)
    comments.value = data
    
    // 初始化回复状态
    comments.value.forEach(comment => {
      showReply.value[comment.id] = false
      replyContent.value[comment.id] = ''
      
      // 初始化回复数据
      if (!comment.replies) {
        comment.replies = []
      }
    })
  } catch (error: any) {
    console.error('获取评论失败', error)
  }
}

// 获取用户头像
const getAvatar = (username: string) => {
  const initials = username?.charAt(0)?.toUpperCase() || 'U'
  return `https://picsum.photos/100/100?random=${initials}`
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (minutes < 1440) {
    return `${Math.floor(minutes / 60)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 显示回复框
const replyComment = (commentId: string) => {
  showReply.value[commentId] = true
  // 自动聚焦到输入框
  nextTick(() => {
    const input = document.querySelector(`.reply-input[comment-id="${commentId}"]`) as HTMLInputElement
    if (input) {
      input.focus()
    }
  })
}

// 提交回复
const submitReply = async (commentId: string) => {
  const content = replyContent.value[commentId].trim()
  if (!content) {
    return
  }
  
  try {
    // 在前端临时添加回复
    const commentIndex = comments.value.findIndex(c => c.id === commentId)
    if (commentIndex !== -1) {
      comments.value[commentIndex].replies.push({
        id: new Date().getTime().toString(),
        author: userStore.user?.username || '匿名用户',
        content,
        createdAt: new Date().toISOString()
      })
      
      // 清空输入框
      replyContent.value[commentId] = ''
      showReply.value[commentId] = false
      
      ElMessage.success('回复成功')
    }
  } catch (error: any) {
    console.error('回复失败', error)
    ElMessage.error('回复失败，请重试')
  }
}

// 点赞评论
const likeComment = (commentId: string) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  
  const commentIndex = comments.value.findIndex(c => c.id === commentId)
  if (commentIndex !== -1) {
    const comment = comments.value[commentIndex]
    
    // 检查是否已点赞
    if (comment.likes?.includes(userStore.user?.id)) {
      // 取消点赞
      comment.likes = comment.likes?.filter(id => id !== userStore.user?.id)
    } else {
      // 点赞
      comment.likes = [...(comment.likes || []), userStore.user?.id]
    }
  }
}
</script>

<style scoped>
.comment-list-container {
  margin-top: 20px;
}

.comment-list {
  margin-bottom: 0;
}

.comment-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-avatar {
  margin-right: 15px;
}

.commenter-info {
  flex: 1;
}

.commenter-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #303133;
}

.comment-time {
  font-size: 14px;
  color: #909399;
}

.comment-content {
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.comment-actions {
  display: flex;
  align-items: center;
}

.comment-actions .el-button {
  padding: 0 10px;
  font-size: 14px;
  color: #909399;
}

.reply-list {
  margin-top: 20px;
  padding-left: 60px;
}

.reply-item {
  padding: 10px 0;
  border-bottom: 1px dashed #ebeef5;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-avatar {
  margin-right: 10px;
}

.reply-content {
  display: inline-block;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.reply-author {
  font-weight: 600;
  color: #409EFF;
  margin-right: 5px;
}

.reply-input {
  width: 80%;
  margin-right: 10px;
  vertical-align: bottom;
}

.reply-button {
  vertical-align: bottom;
}
</style>